package com.platform.security;

import com.platform.common.logger.annotation.EnableLogger;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

public class PlatformAccessDecisionManager implements AccessDecisionManager {

    @EnableLogger
    private static Logger logger;

	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
        logger.info(object.toString()); // object is a URL.
		// 获取请求资源所需要的权限图
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		while (ite.hasNext()) {
			ConfigAttribute configAttribute = ite.next();
			String needPermission = configAttribute.getAttribute();
			// 用户所拥有的权限authentication
			for (GrantedAuthority ga : authentication.getAuthorities()) {
                logger.debug("用 " +  ga.getAuthority() + "   " + needPermission);
				if (needPermission.equals(ga.getAuthority())) { // ga is user's role.
                    logger.debug("有权限访问该资源");
					return;
				}
			}
		}
		// 没有权限则返回异常
        logger.debug("您没有权限访问资源");
		throw new AccessDeniedException("您没有权限访问资源");
	}

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

}
